package com.csmy.my.center.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.TimeZone;

import javax.naming.NamingException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.StrutsRequestWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.jndi.SimpleNamingContextBuilder;
import org.springframework.stereotype.Controller;

import aaaCfg.IocX;

import com.attilax.io.pathx;
import com.attilax.laisens.LaisensManger;
import com.attilax.laisens.OverTimeEx;
import com.attilax.spri.SpringUtil;
import com.attilax.util.CstGettor;
import com.attilax.util.StrutsX;
import com.csmy.my.center.module.CustomerInfo;
import com.csmy.my.center.module.UserInfo;
import com.csmy.my.center.service.UserInfoService;
import com.csmy.my.center.util.CTConstants;
import com.csmy.my.center.util.CTUtils;
import com.csmy.my.center.util.StringUtil;
import com.csmy.my.center.util.dataconvert.Dto;
import com.csmy.my.center.util.dataconvert.impl.BaseDto;
@Controller
public class RequestFilter implements Filter {
	@Autowired
	private UserInfoService userInfoService;
	
	public static void main(String[] args) throws IllegalStateException,
			NamingException {
	  System.setProperty("java.naming.factory.initial", "001115555100");

		String p = pathx.classPath() + "/";
		SpringUtil.locations = new String[] { p + "applicationContext.xml",
				p + "jndi4t.xml" };

		DataSource ds = (DataSource) SpringUtil.getBean("dataSource");
		SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
		builder.bind("java:/comp/env/jndi/wxb_site_new", ds);
		builder.activate();
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
	UserInfo	userInfo;
	
	userInfo	=(UserInfo) session.getAttribute(CTConstants.SESSION_USER);
	if(userInfo==null)
	{
		UserInfoService userInfoService = (UserInfoService) SpringUtil
				.getBean("userInfoService");
		
		Dto pDto = new BaseDto();
		pDto.put("user_id", "23946449");
		 	  userInfo = userInfoService.checkLogin(pDto);
	}
		System.out.println(userInfo.getUser_name());
	}
	
	@SuppressWarnings("static-access")
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain filterChain) throws ServletException, IOException {
		System.out.println("--");
//		try {
//			LaisensManger
//					.checkOvertime("2015-08-23", CstGettor.getDateFrmNet());
//		} catch (OverTimeEx e2) {
//			// TODO Auto-generated catch block
//			e2.printStackTrace();
//			throw new RuntimeException(e2);
//		}
		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpServletResponse response = (HttpServletResponse) arg1;
		HttpSession session = request.getSession();
		String path = request.getContextPath();
		String uri = request.getRequestURI();
		StringUtil.xprint("请求路径为:" + uri);//待处理 session问题
		System.out.println("请求主机为:" + request.getRemoteHost());
		//获取session信息
		UserInfo userInfo = (UserInfo)session.getAttribute(CTConstants.SESSION_USER);//后台用户
		if (userInfo == null) {
			if (userInfoService == null)
			{
				
				SpringUtil sprx=(SpringUtil) IocX.ini().get("sprx");
				userInfoService = (UserInfoService) sprx
						.getBean("userInfoService");
			}
			try{
			userInfo = new AuthorizationInterceptor().getCurUserInfo(request,
					userInfoService);
			}catch(Throwable t)
			{
				t.printStackTrace();
			}
		}
	//	return ui;
		
		CustomerInfo customerInfo = (CustomerInfo)session.getAttribute(CTConstants.SESSION_CUSER);//客户后台
		if(CTUtils.isEmpty(userInfo) && CTUtils.isEmpty(customerInfo) && isnotExtUrl(request)){//如果全部为空
			if ((uri.indexOf("login") == -1) && !uri.equals(path + "/")) {
				System.out.println("客户端未登录，请登录...");
				PrintWriter out = response.getWriter();
				request.setCharacterEncoding("UTF-8");
				response.setContentType("text/html;charset=UTF-8");
				if (uri.indexOf(".jsp") >= 0) {
					System.out.println("截取jsp请求");
					response.sendRedirect(path + "/login.htm");
					return;
				}
			}
		}
		
		filterChain.doFilter(new StrutsRequestWrapper((HttpServletRequest) request), response);  
		//filterChain.doFilter(arg0, arg1);
	}

	/**
	 * is MustCheckUrl by struts 
	attilax    2016年4月23日  下午5:21:15
	 * @param request
	 * @return
	 */
	private boolean isnotExtUrl(HttpServletRequest request) {
		try{
		String f = pathx.classPath() + "/struts.xml";
		String pats =StrutsX. get_excludePattern(f);
		
		return !new StrutsX().isUrlExcluded(request, pats);
		}catch(Exception e){
			System.out.println("isnotExtUrl"+ e.getMessage());
			return false;
		}
	}

	public void destroy() {
		StringUtil.xprint("请求拦截器成功注销....");
	}

	public void init(FilterConfig arg0) throws ServletException {
		StringUtil.xprint("请求拦截器初始化开始....");
		TimeZone zone = TimeZone.getTimeZone("ETC/GMT-8");
		TimeZone.setDefault(zone);
	}
}
